package store

import (
	"editor/constant"
	"editor/utils"
	"fmt"
	"github.com/BurntSushi/toml"
	"github.com/gin-gonic/gin"
	"github.com/radovskyb/watcher"
	"os"
	"sync"
	"time"
)

var (
	confOnce sync.Once
)

func loadConf() (err error) {
	path, _ := os.Getwd()
	configPath := path + constant.ConfFile
	_, err = toml.DecodeFile(configPath, &constant.Config)
	if err != nil {
		err = fmt.Errorf("toml.DecodeFile failed configPath:%s, error:%v\n", configPath, err)
		return
	}
	return nil
}

func confInit(ctx *gin.Context) (err error) {

	confOnce.Do(func() {
		err = loadConf()
	})

	return
}

func WatchConf() (err error) {

	w := watcher.New()
	w.SetMaxEvents(1)
	w.FilterOps(watcher.Write)

	ctx := utils.CreateTestCtx()

	go func() {
		for {
			select {
			case event := <-w.Event:
				if event.Op.String() == "WRITE" {
					fmt.Println("config change...")
					_ = loadConf()
					_ = reloadDB(ctx)
				}
			case err = <-w.Error:
				err = fmt.Errorf("watch config failed, error:%v\n", err)
				return
			case <-w.Closed:
				return
			}
		}
	}()
	path, _ := os.Getwd()
	if err = w.Add(path + constant.ConfFile); err != nil {
		err = fmt.Errorf("watch add file failed, error:%v\n", err)
		return err
	}
	go func() {
		w.Wait()
		w.TriggerEvent(watcher.Write, nil)
	}()

	if err := w.Start(time.Millisecond * 100); err != nil {
		err = fmt.Errorf("watch start failed, error:%v\n", err)
	}

	return
}
